package com.jwgf.report;

import com.jwgf.mqtt.json.JsonBuilder;

import java.util.concurrent.TimeUnit;

import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class ShiftManager {

    private static String SHIFT_TIME_ARRIVED_ACTION = "intent.actions.TIME_ARRIVED";

    private ShiftChangeOperations sco;
    private static ShiftManager sm = new ShiftManager();

    private ShiftManager() {
    }

    public static ShiftManager getInstance() {
        return sm;
    }

    public void init(ShiftChangeOperations sco) {
        this.sco = sco;
        JsonBuilder.start();
        changeShift();
        Observable.interval(10, TimeUnit.SECONDS)
                .observeOn(Schedulers.io())
                .subscribe(new Consumer<Long>() {
            @Override
            public void accept(Long aLong) throws Exception {
                changeShift();
            }
        });
    }

    private void changeShift() {
        if (ShiftTimeRule.getInstance().isShiftChanged()) {
            JsonBuilder.stop();
            JsonBuilder.sendReport();
            sco.doShiftChange();
            ShiftTimeRule.getInstance().updateTimeRange();
            JsonBuilder.start();
        }
    }

}
